package com.app.miwawa.api.system.service.bo;

import java.io.File;
import java.security.MessageDigest;
import java.util.Date;

import javax.annotation.Resource;

import org.framework.common.api.entity.CommonEntityAware;
import org.framework.common.api.service.bo.CommonBoAdapter;
import org.framework.common.api.service.dao.CommonDaoAware;
import org.framework.common.api.support.constant.SystemConstants;
import org.framework.common.api.support.model.ProcessModel;
import org.framework.common.ext.util.AntSqlUtil;
import org.framework.common.ext.util.StringUtil;
import org.framework.common.ext.util.SystemUtils;
import org.framework.common.ext.util.datasource.DynamicDataSourceConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.app.miwawa.api.system.entity.Admin;
import com.app.miwawa.api.system.entity.Center;
import com.app.miwawa.api.system.service.dao.CenterDao;
import com.netease.api.post.NIMResponse;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.framework.common.ext.util.UUIDUtils;

import java.util.ArrayList;
import java.util.List;
/**
 * 业务接口
 * <p>描述: 机构注册－业务接口</p>
 * <p>Company: Professional</p>
 * @author chanlong(陈龙)
 * @date 2016年1月23日 上午9:37:10
 * @version 1.0.2016
 */
@SuppressWarnings("deprecation")
@Service("centerBo")
public class CenterBo extends CommonBoAdapter<Center, String> {
	
	@Autowired
	private CenterDao centerDao;
	
	@Resource(name = "defaultDao")
	private CommonDaoAware<CommonEntityAware<String>, String> defaultDao;

	/**
	 * @see org.framework.common.api.service.bo.CommonBoAdapter#insert(org.framework.common.api.entity.CommonEntityAware)
	 * @author chanlong(陈龙)
	 * @date 2016年1月23日 上午9:44:41
	 */
	@Override
	public Center insert(final Center entity) throws Exception {
		String dburl = entity.getDburl();
		String dbname = entity.getDbname();
		
		ProcessModel process = ProcessModel.factory();
		// 创建数据库
		process.jdbc.update(process.properties.getProperty("center.create.database",dbname));
		
		// 创建数据源配置文件
		DynamicDataSourceConfig.create(dbname, dburl);
		
		Long start = System.currentTimeMillis()/1000;
		// 创建表,视图,存储过程,函数
		AntSqlUtil.execute("/config/properties/db.properties", dbname, new File("D:\\sql\\ddl.sql"));
		
		Long end = System.currentTimeMillis()/1000;
		
		System.out.println("数据库 ："+dbname+"的表、视图、存储过程、函数已创建完毕，共耗时 ："+(end - start)+"秒");
		// 保存实体
		Center center = centerDao.save(entity);
		
		if(createAccid(dbname) == 200){
			process.jdbc.update(process.properties.getProperty("im.create.accid"),dbname ,dbname);
			System.out.println("云信账号 : "+dbname+"添加成功");
		}else{
			System.out.println("云信账号 : "+dbname+"添加失败");
		}
		
		// 保存管理员
		saveAdmin(center);
		
		return center;
	}
	
	public void remove(final String dbname) throws Exception {
		ProcessModel process = ProcessModel.factory();
		
		// 删除数据库
		process.jdbc.update(process.properties.getProperty("center.drop.database",dbname));
		
		process.jdbc.update(process.properties.getProperty("center.delete.dbname"),dbname);
	}
	
	/**
	 * 查询最大编码.
	 * @return
	 * @author chanlong(陈龙)
	 * @date 2016年1月23日 下午5:36:44
	 */
	public String maxcode(){
		String code = centerDao.maxcode();
		return SystemUtils.maxcode(Center.CODE_PREFIX_CENTER, code, Center.DEFAULT_CODE_SERIAL);
	}
	
	/*
	 * 保存各机构的系统管理员
	 */
	private void saveAdmin(final Center center) throws Exception{
		Admin admin = new Admin();
		admin.setType(SystemConstants.DEFAULT_CENTER);
		admin.setName(SystemConstants.DEFAULT_ADMIN);
		admin.setEmail(SystemConstants.DEFAULT_VALUE);
		admin.setMobile(center.getMobile());
		admin.setAccount(center.getDbname());
		admin.setPassword(StringUtil.DEFAULT_PASSWORD);
		admin.setCreateDate(new Date());
		admin.setCenter(center.getName());
		admin.setCenterid(center.getId());
		admin.setStatus(SystemConstants.DICT_STATUS_DEFAULT);
		admin.setInvalid(SystemConstants.DICT_DELETE_INVALID);
		
		defaultDao.insert(admin);
	}
	
	public static void main(String[] args) {
		AntSqlUtil.execute("/config/properties/db.properties", "miwawa_0test", new File("D:\\sql\\dataTransmission.sql"));
	}
	
	@SuppressWarnings("resource")
	public Integer createAccid(final String dbname) throws Exception{
		DefaultHttpClient httpClient = new DefaultHttpClient();
        String url = "https://api.netease.im/nimserver/user/create.action";
        HttpPost httpPost = new HttpPost(url);

        String appKey = "591e21871ef0f634b660c552d66b3a25";
        String appSecret = "633f176c3ab0";
        String nonce =  UUIDUtils.getUUID();
        String curTime = String.valueOf((new Date()).getTime() / 1000L);
        String checkSum = getCheckSum(appSecret, nonce ,curTime);//参考 计算CheckSum的java代码

        // 设置请求的header
        httpPost.addHeader("AppKey", appKey);
        httpPost.addHeader("Nonce", nonce);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

        // 设置请求的参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("accid", dbname));
		httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
		// 执行请求
        HttpResponse response = httpClient.execute(httpPost);
        // 打印执行结果
        String result = EntityUtils.toString(response.getEntity(), "utf-8");
        System.out.println(result);
        NIMResponse res =  new NIMResponse(result);
        System.out.println(res.getCode()+"-----------------------------");
        return res.getCode();
	}
	
	// 计算并获取CheckSum
    public static String getCheckSum(String appSecret, String nonce, String curTime) {
        return encode("sha1", appSecret + nonce + curTime);
    }
    
    private static String encode(String algorithm, String value) {
        if (value == null) {
            return null;
        }
        try {
            MessageDigest messageDigest
                    = MessageDigest.getInstance(algorithm);
            messageDigest.update(value.getBytes());
            return getFormattedText(messageDigest.digest());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
	
    private static String getFormattedText(byte[] bytes) {
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        for (int j = 0; j < len; j++) {
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        return buf.toString();
    }
    private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
}
